/*
Copyright (c) 2011, Stephane Albert
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the organization nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL STEPHANE ALBERT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "debridDownloader.h"

std::map<std::string, std::string> debridDownloader::htmlChars;

debridDownloader::debridDownloader() {
    curlHandle = NULL;
    initCURL();
}

debridDownloader::debridDownloader(CURL *copyHandle) {
    curlHandle = NULL;
    if (copyHandle)
        curlHandle = curl_easy_duphandle(copyHandle);
    if (!curlHandle)
        initCURL();
}

debridDownloader::~debridDownloader() {
    unloadCURL();
}

bool debridDownloader::initCURL() {
    unloadCURL();
    curlHandle = curl_easy_init();
    if (curlHandle != NULL)
        return true;
    return false;
}

bool debridDownloader::loadCURLSettings() {
    if (curlHandle != NULL) {
        curl_easy_reset(curlHandle);
        curl_easy_setopt(curlHandle, CURLOPT_USERAGENT, USER_AGENT);    //Send user agent (mandatory for real-debrid)
        curl_easy_setopt(curlHandle, CURLOPT_ENCODING, "");             //Set default encoding to accept compressed pages (mandatory for filecrop)
        curl_easy_setopt(curlHandle, CURLOPT_COOKIEFILE, "");           //Set auto cookies
        curl_easy_setopt(curlHandle, CURLOPT_MAXREDIRS, MAX_REDIRS);    //Follow location trap (deadlock)
        return true;
    }
    return false;
}

void debridDownloader::unloadCURL() {
    if (curlHandle != NULL) {
        curl_easy_cleanup(curlHandle);
        curlHandle = NULL;
    }
}

size_t debridDownloader::dataToStr(void *rawBuffer, size_t size, size_t nmemb, void *strPtr) {
    if (rawBuffer == NULL)
        return 0;
    std::string *outputString = (std::string*)strPtr;
    size_t initLen = outputString->length();
    outputString->append((char*)rawBuffer, size*nmemb);
    return outputString->length() - initLen;
}

size_t debridDownloader::dataToFile(void *rawBuffer, size_t size, size_t nmemb, void *filePtr) {
    if (rawBuffer == NULL)
        return 0;
    std::ofstream *outputFile = (std::ofstream*)filePtr;
    if (!outputFile->good())
        return 0;
    std::streampos initPos = outputFile->tellp();
    outputFile->write((const char*)rawBuffer, size*nmemb);
    return outputFile->tellp() - initPos;
}

size_t debridDownloader::fileToData(void *rawBuffer, size_t size, size_t nmemb, void *filePtr) {
    if (rawBuffer == NULL)
        return CURL_READFUNC_ABORT;
    std::ifstream *inputFile = (std::ifstream*)filePtr;
    if (inputFile->eof())
        return 0;
    inputFile->read((char*)rawBuffer, size*nmemb);
    return inputFile->gcount();
}

int debridDownloader::seekFile(void *instream, curl_off_t offset, int origin) {
    if (instream == NULL)
        return CURL_SEEKFUNC_FAIL;
    std::ofstream *outputFile = (std::ofstream*)instream;
    if (!outputFile->good())
        return CURL_SEEKFUNC_FAIL;
    switch (origin) {
        case SEEK_SET: outputFile->seekp(offset, std::ios_base::beg);
            break;
        case SEEK_CUR: outputFile->seekp(offset);
            break;
        case SEEK_END: outputFile->seekp(offset, std::ios_base::end);
            break;
        default:
            return CURL_SEEKFUNC_FAIL;
    }
    return CURL_SEEKFUNC_OK;
}

std::string debridDownloader::postData(const std::string& URL, const std::string& postData) {
    if (curlHandle != NULL) {
        std::string outputData;
        loadCURLSettings();
        curl_easy_setopt(curlHandle, CURLOPT_URL, URL.c_str());
        curl_easy_setopt(curlHandle, CURLOPT_POSTFIELDS, postData.c_str());
        curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, dataToStr);
        curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, &outputData);
        CURLcode retCode = curl_easy_perform(curlHandle);
        if (retCode == CURLE_OK)
            return outputData;
    }
    return "";
}

std::string debridDownloader::postFile(const std::string& URL, const std::string& filePath) {
    if (curlHandle != NULL || filePath.empty()) {
        std::ifstream inputData(filePath.c_str(), std::ios_base::binary|std::ios_base::in);
        if (!inputData.is_open())
            return "";
        inputData.seekg(0, std::ios::end);
        std::streampos fileSize = inputData.tellg();
        inputData.seekg(0, std::ios::beg);
        std::string outputData;
        loadCURLSettings();
        curl_easy_setopt(curlHandle, CURLOPT_VERBOSE, 1L);
        curl_easy_setopt(curlHandle, CURLOPT_URL, URL.c_str());
        curl_easy_setopt(curlHandle, CURLOPT_POST, 1);
        curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, dataToStr);
        curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, &outputData);
        curl_easy_setopt(curlHandle, CURLOPT_READFUNCTION, fileToData);
        curl_easy_setopt(curlHandle, CURLOPT_READDATA, &inputData);
        curl_easy_setopt(curlHandle, CURLOPT_POSTFIELDSIZE, (long)fileSize);
        CURLcode retCode = curl_easy_perform(curlHandle);
        if (retCode == CURLE_OK)
            return outputData;
    }
    return "";
}

std::string debridDownloader::postMultiPart(const std::string& URL, curl_httppost *formPost) {
    if (curlHandle != NULL && formPost != NULL) {
        std::string outputData;
        loadCURLSettings();
        curl_easy_setopt(curlHandle, CURLOPT_URL, URL.c_str());
        curl_easy_setopt(curlHandle, CURLOPT_HTTPPOST, formPost);
        curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, dataToStr);
        curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, &outputData);
        CURLcode retCode = curl_easy_perform(curlHandle);
        if (retCode == CURLE_OK)
            return outputData;
    }
    return "";
}



std::string debridDownloader::getData(const std::string& URL, bool follow) {
    if (curlHandle != NULL) {
        std::string outputData;
        loadCURLSettings();
        curl_easy_setopt(curlHandle, CURLOPT_URL, URL.c_str());
        curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, dataToStr);
        curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, &outputData);
        if (follow)
            curl_easy_setopt(curlHandle, CURLOPT_FOLLOWLOCATION, 1);
        CURLcode retCode = curl_easy_perform(curlHandle);
        if (retCode == CURLE_OK)
            return outputData;
    }
    return "";
}

std::string debridDownloader::urlEncode(const std::string& rawURL) {
    std::string encodedURL;
    if (curlHandle != NULL) {
        char *escapedURL;
        escapedURL = curl_easy_escape(curlHandle, rawURL.c_str(), rawURL.length());
        if (escapedURL != NULL) {
            encodedURL = escapedURL;
            curl_free(escapedURL);
        }
    }
    return encodedURL;
}

std::string debridDownloader::urlDecode(const std::string& rawURL) {
    std::string decodedURL;
    if (curlHandle != NULL) {
        char *unescapedURL;
        unescapedURL = curl_easy_unescape(curlHandle, rawURL.c_str(), rawURL.length(), NULL);
        if (unescapedURL != NULL) {
            decodedURL = unescapedURL;
            curl_free(unescapedURL);
        }
    }
    return decodedURL;
}

std::string debridDownloader::htmlEncode(const std::string& rawString) {
    if (htmlChars.empty())
        initHtmlChars();
    std::string result = rawString;
    std::map<std::string, std::string>::iterator curPos = htmlChars.begin();
    std::map<std::string, std::string>::iterator endPos = htmlChars.end();
    size_t lastFound;
    while (curPos != endPos) {
        lastFound = result.find(curPos->first);
        while (lastFound != std::string::npos) {
            result.replace(lastFound, curPos->first.size(), curPos->second);
            lastFound += curPos->second.size();
            lastFound = result.find(curPos->first, lastFound);
        }
        ++curPos;
    }
    return result;
}

std::string debridDownloader::htmlDecode(const std::string& rawString) {
    if (htmlChars.empty())
        initHtmlChars();
    std::string result = rawString;
    std::map<std::string, std::string>::iterator curPos = htmlChars.begin();
    std::map<std::string, std::string>::iterator endPos = htmlChars.end();
    size_t lastFound;
    while (curPos != endPos) {
        lastFound = result.find(curPos->second);
        while (lastFound != std::string::npos) {
            result.replace(lastFound, curPos->second.size(), curPos->first);
            lastFound += curPos->first.size();
            lastFound = result.find(curPos->second, lastFound);
        }
        ++curPos;
    }
    return result;
}

void debridDownloader::initHtmlChars() {
    htmlChars.clear();
    htmlChars.insert(std::pair<std::string, std::string>("&", "&amp;"));
    htmlChars.insert(std::pair<std::string, std::string>("<", "&lt;"));
    htmlChars.insert(std::pair<std::string, std::string>(">", "&gt;"));
    htmlChars.insert(std::pair<std::string, std::string>("\"", "&quot;"));
    htmlChars.insert(std::pair<std::string, std::string>("'", "&#039;"));
    htmlChars.insert(std::pair<std::string, std::string>(" ", "&nbsp;"));
    htmlChars.insert(std::pair<std::string, std::string>("£", "&pound;"));
    htmlChars.insert(std::pair<std::string, std::string>("à", "&agrave;"));
    htmlChars.insert(std::pair<std::string, std::string>("ç", "&ccedil;"));
    htmlChars.insert(std::pair<std::string, std::string>("è", "&egrave;"));
    htmlChars.insert(std::pair<std::string, std::string>("é", "&eacute;"));
    htmlChars.insert(std::pair<std::string, std::string>("ê", "&ecirc;"));
    htmlChars.insert(std::pair<std::string, std::string>("ù", "&ugrave;"));
    htmlChars.insert(std::pair<std::string, std::string>("©", "&copy;"));
    htmlChars.insert(std::pair<std::string, std::string>("Ã", "&Atilde;"));
}
